import axios from 'axios';
import {
  MessageBox,
  Message
} from 'element-ui';
import store from '@/store';
import {
  getToken,
  setToken
} from '@/utils/auth';

function ctx(o, n) {
  let curr = '';
  for (let i in n) {
    curr = n[i];
    if (o[i] && !!curr) {
      o[i] = curr;
    }
  }
  curr = null;
}

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  headers: {
    'Content-Type': 'application/json'
  },
  withCredentials: true,
  timeout: 30000
});

service.interceptors.request.use(
  (config) => {
    let {
      token
    } = store.getters;
    let {
      options,
      headers
    } = config;

    if (!headers.notoken && token) {
      config.headers['jwt-token'] = encodeURIComponent(token || getToken());
    } else { 
      delete headers.notoken;
    }!!options ? ctx(config, options) : '';

    // console.log(config);

    return config;
  },
  (error) => {
    console.log(error);
    return Promise.reject(error);
  }
);

service.interceptors.response.use(
  (response) => {
    let {
      data
    } = response;
    let {
      code,
      result,
      msg
    } = data;
    if (code !== 200) {
      Message({
        message: msg || 'Error',
        type: 'error',
        duration: 5 * 1000
      });

      if (code === 1001 || code === 404 || code === 50014) {
        console.log('-----------------=======================');
        MessageBox.confirm(msg, '错误提示', {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(
          () => {
            store.dispatch('user/resetToken').then(() => {
              // console.log('login');
              // this.$router.push(`/login?redirect=${this.$route.fullPath}`);
              location.reload();
            });
          },
          () => {
            return Promise.reject(new Error(msg || 'Error'));
          }
        );
      } else if (code === 1002) {
        //  接口没有权限
      }
      return Promise.reject(new Error(msg || 'Error'));
    } else {
      let jwttoken = response.headers['jwt-token'];
      // console.log('---------------------------------------------');
      // console.log(response.headers);
      // console.log(jwttoken);
      if (!!jwttoken) {
        store.dispatch('user/setToken', jwttoken);
      }
      return {
        result: result,
        e: data
      };
    }
  },

  (error) => {
    console.log('error==>>', error); // for debug
    Message({
      message: error.message || error || '接口出现错误，请稍后再试',
      type: 'error',
      duration: 5 * 1000
    });
    return Promise.reject(error);
  }
);

export default service;
